package com.csd.jwt.filter;

import com.csd.jwt.util.JWTUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @className: AuthFilter
 * @description:
 * @author: 刘子奇
 * @date: 2019/12/10 15:33
 **/
@Component
public class AuthFilter extends ZuulFilter {
    private final static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(AuthFilter.class);

    //非拦截地址
    private List<String> paths;

    public AuthFilter() {
        super();
        paths = new ArrayList<>();
        paths.add("/api-auth/login");
        paths.add("/**/swagger**/**");
        paths.add("/**/v2/api-docs");
        paths.add("/**/*.css");
        paths.add("/**/*.jpg");
        paths.add("/**/*.png");
        paths.add("/**/*.gif");
        paths.add("/**/*.js");
        paths.add("/**/*.svg");
    }

    @Override
    public String filterType() {
        return "pre";// 指定过滤器类型
    }

    @Override
    public int filterOrder() {
        return 0;// 过滤器顺序，数字越小越先执行
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String uri=request.getRequestURI();
        LOGGER.info("uri:{}", uri);
        PathMatcher matcher = new AntPathMatcher();
        Optional<String> optional =paths.stream().filter(t->matcher.match(t,uri)).findFirst();
        return !optional.isPresent();// 是否使用该过滤器
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
//        HttpServletResponse response = requestContext.getResponse();
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Headers", "Authorization,X-Requested-With");
        String requestUri = request.getRequestURI();
        LOGGER.info("uri：{}",requestUri);
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.setResponseBody("token is empty");
            return null;
        }
        if (!JWTUtil.verify(token)) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.setResponseBody("token is not effective");
            return null;
        }
        LOGGER.info("authorization");
        return null;
    }
}
